// pages/memberCard/memberCard.js
const redPacketService = require('../../../../api/redPacketService.js')
const memberService = require('../../../../api/memberService.js')
const wxbarcode = require('../../../../utils/self.js');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    memberId: '3232232323236569',
    codeWidth: 586,
    codeHeight: 174,
    hasUserInfo: false,
    time: '',
    codeType: 'BARCODE',
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false
    },
    redPacket: true,
    animationData: {},
    animationRotate: {},
    moneyAmount: '0.00',
    homeBack: false,
    popupTop: true,
    phone: false
  },
  toHome: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 刷新付款码
  refreshMbrCode: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      if (this.data.codeType !== 'BARCODE') {
        this.getMbrCode()
      }
    } else {
      console.log()
      wx.showToast({
        title: '您还没有登陆哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 获取会员码
   */
  getMbrCode: function () {
    const that = this
    clearTimeout(this.data.time)
    memberService.getMbrCode().then(res => {
      console.log(res)
      if (res.codeType === 'BARCODE') {
        this.setData({
          memberId: res.code,
          codeType: res.codeType
        })
      } else {
        this.setData({
          memberId: res.code,
          codeType: res.codeType
        })
      }
      if (res.codeType === 'BARCODE') {
        wxbarcode.barcode('barcode', this.data.memberId, this.data.codeWidth, this.data.codeHeight);
      } else {
        wxbarcode.qrcode('qrcode', res.code, 280, 280);
      }
      this.setData({
        memberId: this.phoneSeparated(res.code)
      })
      if (this.data.codeType !== 'BARCODE' && res.integer) {
        let integerTime = res.integer * 1000
        var time = setTimeout(() => {
          this.getMbrCode()
          console.log('刷新了')
        }, integerTime);
        that.setData({
          time: time
        })
      }
      return res
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    const that = this
    var pageStack = getCurrentPages()
    if (pageStack.length === 1) {
      this.setData({
        homeBack: true
      })
    }
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        that.getMbrCode()
        that.setData({
          hasUserInfo: true
        })
        redPacketService.checkCanJoin().then(res => {
          console.log(res)
          if (res.canJoin) {
            that.setData({
              acyivityId: res.acyivityId
            })
            that.toggleMiddlePopup()
          } else {}
        }).catch(err => {
          console.log(err.message)
          if (err.message !== '您还没有登录哦~') {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          }
        })
        var animation = wx.createAnimation({
          duration: 1000,
        })
        this.animation = animation
      } else {
        that.handlePopupPhone()
      }
    } else {
      this.setData({
        hasUserInfo: false
      })
    }
  },
  // 数字处理
  codeTextPartition: function (val) {
    console.log(val)
    val = val.replace(/\s/g, '').replace(/(\w{4})(?=\w)/g, "$1 ");
    console.log(val)
    return val;
  },
  // 手机号处理
  phoneSeparated: function (phoneNumber) {
    let tel = trim(phoneNumber, 'g');
    if (isPhone(tel)) {
      tel = tel.substring(0, 3) + ' ' + tel.substring(3, 7) + ' ' + tel.substring(7, 11);
    } else {
      tel = this.codeTextPartition(tel)
    }
    return tel;
    // 去掉字符串中所有空格(包括中间空格,需要设置第2个参数为:g)
    function trim(str, is_global) {
      var result;
      result = str.replace(/(^\s+)|(\s+$)/g, "");
      if (is_global && is_global.toLowerCase() == "g") {
        result = result.replace(/\s/g, "");
      }
      return result;
    }
    // 判断是否是手机号码格式
    function isPhone(str) {
      var reg = /^1(3|4|5|7|8)\d{9}$/;
      return reg.test(trim(str, 'g'));
    }
  },
  // 检查当前用户是否登录授权
  checkAuth: function (e) {
    console.log(e)
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  // 前往微信支付
  toWeixinPay: function () {
    wx.openOfflinePayView({
      success: function (res) {
        console.log(res.data)
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  // 前往余额支付
  tobalancePay: function () {
    const that = this
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        wx.navigateTo({
          url: '../../pay/pay/pay'
        })
      } else {
        wx.showToast({
          title: '您还不是会员，请绑定手机号成为会员~',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          that.handlePopupPhone()
        }, 2000);
      }
    } else {
      wx.showToast({
        title: '您还没有登录哦~',
        icon: 'icon',
        duration: 2000
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.time)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '现金红包大派送',
      path: '/pages/mallModule/myCard/memberCard/memberCard',
      imageUrl: 'http://xianfengapp.oss-cn-hangzhou.aliyuncs.com/xianfengImages/iconRedPacketShare.png',
      success(e) {
        wx.showShareMenu({
          withShareTicket: true
        })
      }
    }
  },
  /**
   * 打开弹窗
   */
  toggleMiddlePopup() {
    this.toggle('middle');
  },
  toggle(type) {
    if (!this.data.show[type]) {
      // 打开
      setTimeout(() => {
        this.setData({
          canvasHidden: true
        })
      }, 100);
      this.setData({
        [`show.${type}`]: !this.data.show[type]
      });
    } else {
      // 关闭
      this.setData({
        [`show.${type}`]: !this.data.show[type]
      });
      setTimeout(() => {
        this.setData({
          canvasHidden: false
        })
      }, 100);
    }
  },
  toggleNextStep: function () {
    this.setData({
      step: 'second'
    })
  },
  openRedPacket: function () {
    console.log(this.animation)
    console.log(this.data.acyivityId)
    redPacketService.openRedPacket(this.data.acyivityId).then(res => {
      this.setData({
        moneyAmount: res
      })
      this.animation.rotate3d(0, 180, 0, 360).step({
        duration: 1000
      })
      this.setData({
        animationRotate: this.animation.export()
      })
      setTimeout(() => {
        this.setData({
          redPacket: false
        })
        setTimeout(() => {
          this.setData({
            popupTop: false
          })
          this.animation.currentTransform = []
          console.log(this.animation)
          let y = 382 / 750 * wx.getSystemInfoSync().windowWidth;
          this.animation.translate(0, -y).step({
            duration: 1000
          })
          this.setData({
            animationData: this.animation.export()
          })
        }, 100)
      }, 1000);
    }).catch(err => {
      if (err.code == '38003') {
        this.toggleMiddlePopup('middle')
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  toRedPacket: function () {
    wx.navigateTo({
      url: '../redPacket/redPacket',
    })
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
        self.getMbrCode()
      } else {
        self.setData({
          hasUserInfo: false,
        })
        self.handlePopupPhone()
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false,
        hasUserInfo: true
      })
      this.getMbrCode()
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})